package com.tuzhi.base.web.interceptor;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tuzhi.common.domain.LoginUserBO;
import com.tuzhi.util.UserContext;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;

import static com.tuzhi.common.constants.security.Constants.USER_INFO;

@Component
public class UserInterceptor implements HandlerInterceptor {
//    Logger logger = LoggerFactory.getLogger(UserInterceptor.class);
    static final ObjectMapper MAPPER = new ObjectMapper();

    static {
        MAPPER.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);
        MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String userInfo = request.getHeader(USER_INFO);

        if (StringUtils.isNotBlank(userInfo)) {
            LoginUserBO loginUser = null;//  存储用户信息的实体类
            try {
                 userInfo = URLDecoder.decode(userInfo, StandardCharsets.UTF_8.toString());
                loginUser = MAPPER.readValue(userInfo, LoginUserBO.class);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            if (loginUser != null) {
                UserContext.setUserInfo(loginUser);
            }
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        //log.info("清除了 ThreadLocalContextHolder 的值");
        UserContext.clear();
    }
}